package com.luo.demo.multi.ds.pkg.service.impl;

import com.luo.demo.multi.ds.pkg.entity.MyData;
import com.luo.demo.multi.ds.pkg.mapper.ds1.MyDataMapper1;
import com.luo.demo.multi.ds.pkg.mapper.ds2.MyDataMapper2;
import com.luo.demo.multi.ds.pkg.service.IMyDataService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 我的数据 服务实现类
 * </p>
 *
 * @author luohq
 * @since 2022-08-06
 */
@Service
public class MyDataServiceImpl implements IMyDataService {

    @Resource
    private MyDataMapper1 myDataMapper1;
    @Resource
    private MyDataMapper2 myDataMapper2;

    @Override
    public MyData findByIdFromDs1(Long id) {
        return this.myDataMapper1.selectById(id);
    }

    @Override
    public MyData findByIdFromDs2(Long id) {
        return this.myDataMapper2.selectById(id);
    }

    /**
     * 仅@Primary主数据源ds1支持事务，非主数据源ds2不支持事务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addBothData(MyData myData1, MyData myData2) {
        Integer retCount1 = this.myDataMapper1.insert(myData1);
        Integer retCount2 = this.myDataMapper2.insert(myData2);
        //Integer retCount1 = this.addData1(myData1);
        //Integer retCount2 = this.addData2(myData2);
        if (true) {
            throw new RuntimeException("业务异常 - 制造数据库回滚！");
        }
        return retCount1 + retCount2;
    }

    /**
     * 仅@Primary主数据源支持事务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addData1(MyData myData) {
        Integer retCount = this.myDataMapper1.insert(myData);
        return retCount;
    }

    /**
     * 非主数据源不支持事务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addData2(MyData myData) {
        Integer retCount = this.myDataMapper2.insert(myData);
        return retCount;
    }
}
